<template>
    <div class="container">

        <!-- 面包屑导航栏 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>小区管理</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 模糊搜索框 -->
        <el-row style="margin-top: 10px;">
            <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
                <!-- 小区名称框 -->
                <!-- clearable @clear="queryCommunityList" : 清除搜索内容 -->
                <el-form-item label="小区名称">
                    <el-input clearable @clear="queryCommunityList" v-model="queryInfo.communityName"
                        placeholder="请输入小区名称"></el-input>
                </el-form-item>
                <!-- 创建时间框 -->
                <el-form-item label="创建时间">
                    <el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="date" type="daterange"
                        range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <!-- 搜索框 -->
                <el-form-item>
                    <el-button @click="queryCommunityList" type="primary">搜索</el-button>
                </el-form-item>
            </el-form>
        </el-row>

        <!-- 新增小区按钮 -->
        <el-row style="margin-bottom: 10px;">
            <el-button @click="addcommunity" type="primary">新增小区</el-button>
        </el-row>

        <!-- 表格展示小区信息 -->
        <!-- :header-cell-style="{ backgroundColor: '#1890ff', color: '#fff' }"
        设置表头背景颜色和字体颜色 -->
        <el-table :data="tableData" border :header-cell-style="{ backgroundColor: '#1890ff', color: '#fff' }"
            style="width: 100%">
            <el-table-column align="center" prop="communityId" label="ID">
            </el-table-column>
            <el-table-column align="center" prop="communityName" label="名称">
            </el-table-column>
            <el-table-column align="center" label="位置">
                <!-- 使用作用域插槽 -->
                <template slot-scope="scope">
                    {{ scope.row.communityProvince }}
                    {{ scope.row.communityCity }}
                    {{ scope.row.communityDistrict }}
                    {{ scope.row.communityAddress }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="communityUserCount" label="用户数量">
            </el-table-column>
            <el-table-column align="center" prop="communityShopCount" label="关联门店">
            </el-table-column>
            <el-table-column align="center" prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column align="center" prop="address" label="操作">
                <!-- 使用作用域插槽 -->
                <template slot-scope="scope">
                    <el-link type="primary" :underline="false"
                        @click="queryshop(scope.row.communityId)">查看关联门店</el-link><br>
                    <el-link type="primary" :underline="false"
                        @click="editCommunity(scope.row)">修改</el-link>&nbsp;&nbsp;&nbsp;
                    <el-link type="primary" :underline="false"
                        @click="removeCommunity(scope.row.communityId)">删除</el-link>
                </template>

            </el-table-column>
        </el-table>

        <!-- 分页按钮-->
        <el-row style="margin-top: 10px;">
            <!-- current-page:要访问的页码 -->
            <!-- page-size：每页展示的条数 -->
            <!-- page-sizes：可选择的每页展示的条数 -->
            <!-- total：数据总条数 -->
            <!-- current-change: 当选择页码时触发的函数 -->
            <!-- size-change： -->
            <el-pagination :current-page="queryInfo.pageNum" :page-sizes="[1, 5, 10, 20]"
                :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>
        </el-row>

        <!-- 添加或修改小区的对话框 -->
        <!-- title:对话框名称 -->
        <!-- visible.sync： true对话框显示，false对话框隐藏-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="cancel">
            <el-form :model="community" :rules="rules" ref="community" hide-required-asterisk>
                <el-form-item label="小区名称" prop="communityName" label-width="100px">
                    <el-input placeholder="请输入小区名称" v-model="community.communityName"></el-input>
                </el-form-item>
                <el-form-item label="所属地区" label-width="100px">
                    <el-cascader v-model="address" :options="citys"></el-cascader>
                </el-form-item>
                <el-form-item label="" prop="communityAddress" label-width="100px">
                    <el-input placeholder="请填写详细地址" v-model="community.communityAddress"></el-input>
                </el-form-item>
                <el-form-item label="小区坐标" label-width="100px">
                    <el-button @click="getGeo">获取位置</el-button>
                    <span v-show="community.communityLatitude">{{ community.communityLongitude }},{{
                        community.communityLatitude }}</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="updateCommunity">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 查看关联门店对话框 -->
        <el-dialog title="查看关联门店" :visible.sync="dialogFormVisible2">
            <el-form :inline="true" :model="queryInfo2" class="demo-form-inline">
                <!-- 门店名称框 -->
                <!-- clearable @clear="queryCommunityList" : 清除搜索内容 -->
                <el-form-item label="门店名称">
                    <el-input clearable @clear="searchshop" v-model="queryInfo2.shopName"
                        placeholder="请输入门店名称"></el-input>
                </el-form-item>
                <!-- 搜索框 -->
                <el-form-item>
                    <el-button @click="searchshop">搜索</el-button>
                </el-form-item>
                <el-button @click="addshop">添加关联门店</el-button>
            </el-form>

            <!-- 表格展示门店信息 -->
            <el-table :data="associatedStoresList" border
                :header-cell-style="{ backgroundColor: '#1890ff', color: '#fff' }" style="width: 100%">
                <el-table-column align="center" prop="shopCommunitySort" label="序号">
                </el-table-column>
                <el-table-column align="center" prop="shopName" label="名称">
                </el-table-column>
                <el-table-column align="center" prop="shopId" label="ID">
                </el-table-column>
                <el-table-column align="center" label="排序">
                </el-table-column>
                <el-table-column align="center" prop="shopAddress" label="门店地址">
                </el-table-column>
                <el-table-column align="center" prop="shopOrderCount" label="订单数量">
                </el-table-column>
                <el-table-column align="center" label="操作">
                    <!-- 使用作用域插槽 -->
                    <template slot-scope="scope">
                        <el-button size="mini" @click="removeshop(scope.row.shopId)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 查看关联门店的分页按钮-->
            <el-row style="margin-top: 10px;">
                <el-pagination small :current-page="queryInfo2.pageNum" :page-sizes="[1, 5, 10, 20]"
                    :page-size="queryInfo2.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="storeTotal" @size-change="storehandleSizeChange" @current-change="storehandleCurrentChange">
                </el-pagination>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible2 = false">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 添加关联门店 -->
        <el-dialog title="添加关联门店" :visible.sync="dialogFormVisible3">
            <el-form :inline="true" :model="queryInfo2" class="demo-form-inline">
                <!-- 门店名称框 -->
                <!-- clearable @clear="queryCommunityList" : 清除搜索内容 -->
                <el-form-item label="">
                    <el-input clearable @clear="findShop" v-model="queryInfo2.shopName"
                        placeholder="请输入门店名称"></el-input>
                </el-form-item>
                <!-- 搜索框 -->
                <el-form-item>
                    <el-button @click="findShop">搜索</el-button>
                </el-form-item>
            </el-form>

            <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="findShopList" border
                :header-cell-style="{ backgroundColor: '#1890ff', color: '#fff' }" style="width: 100%">
                <!-- <el-table-column prop="shopCommunitySort" label="序号">
                </el-table-column> -->
                <el-table-column align="center" type="selection" width="55">
                </el-table-column>
                <el-table-column align="center" prop="shopName" label="名称">
                </el-table-column>
                <el-table-column align="center" prop="shopId" label="ID">
                </el-table-column>
                <el-table-column align="center" label="排序">
                </el-table-column>
                <el-table-column align="center" prop="shopAddress" label="坐标">
                </el-table-column>
                <el-table-column align="center" prop="shopOrderCount" label="订单数量">
                </el-table-column>
            </el-table>

            <!-- 添加关联门店的分页按钮-->
            <el-row style="margin-top: 10px;">
                <el-pagination small :current-page="queryInfo2.pageNum" :page-sizes="[1, 5, 10, 20]"
                    :page-size="queryInfo2.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total2"
                    @size-change="handleSizeChange2" @current-change="handleCurrentChange2">
                </el-pagination>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible3 = false">取 消</el-button>
                <el-button type="primary" @click="baocunganlian">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// 导入省市区数据
import citys from "../assets/citydata";
export default {
    data() {
        return {
            // 获取和查询的所有数据参数
            queryInfo: {
                name: '',
                communityName: '',
                startTime: '',
                endTime: '',
                pageNum: 1,
                pageSize: 10
            },
            // 获取和查询的关联门店参数
            queryInfo2: {
                pageNum: 1,
                pageSize: 10,
                shopName: '',
                communityId: ''
            },
            total: null,        // 小区数据总条数
            storeTotal: null,   // 查看关联门店的数据条数
            total2: null,       // 添加关联门店的数据条数
            // 小区信息集合数组
            tableData: [],
            // 关联门店集合数组
            associatedStoresList: [],
            findShopList: [],
            // 选择查询的时间范围/数组
            date: null,
            title: '新增小区',
            dialogFormVisible: false,       // 添加或修改的开关
            dialogFormVisible2: false,      // 查看关联门店的开关
            dialogFormVisible3: false,      // 添加关联门店的开关

            // 小区对象
            community: {
                communityId: "",       // 编号
                communityName: "",         // 小区名称
                communityAddress: "",     // 详细地址
                communityProvince: "",  // 省份
                communityCity: "",    // 城市
                communityDistrict: "",    // 区域
                communityAreaCode: "",       // 区域码
                communityLatitude: "",     // 纬度
                communityLongitude: "",   // 经度
                communityCoordinates: "",   // 全地址
                addOrUpdateFlag: 1  // 添加还是修改
            },
            citys: citys,       // 所有的省市区对象
            address: [],        // 省市区三个数据的数组
            multipleSelection: [],  // 选中的添加门店数组

            fendeShopCommunityList: [], // 选中的添加门店的id数组

            // form表单验证规则
            rules: {
                communityName: [
                    { required: true, message: '请输入小区名称', trigger: 'blur' },
                ],
                communityAddress: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' },
                ],
            }
        }
    },
    methods: {
        // 关联门店最里面点击搜索想要门店
        findShop() {
            this.findShopListByAdd()
        },
        // 点击保存，保存关联门店,进行关联
        baocunganlian() {
            for (let i in this.multipleSelection) {
                this.fendeShopCommunityList.push(this.multipleSelection[i].shopId)
            }
            // console.log(this.multipleSelection);
            // console.log(this.fendeShopCommunityList);
            this.$http.post('associatedStores/addAssociatedStores', {
                fendeShopCommunityList: this.fendeShopCommunityList,
                panghuCommunityId: this.queryInfo2.communityId
            })
                .then(res => {
                    console.log(res);
                    if (res.data.status == 200) {
                        this.$message.success('添加成功')
                        this.fendeShopCommunityList = []    // 保存后重置选中的门店id
                        this.dialogFormVisible3 = false  // 保存后关闭页面
                        this.queryCommunityList()
                        this.queryshoplist()
                    } else {
                        this.$message.error('添加失败')
                    }
                })
        },
        // 添加关联门店
        addshop() {
            this.dialogFormVisible3 = true
            this.findShopListByAdd()
        },
        // 查看关联门店点击触发事件
        queryshop(id) {
            this.dialogFormVisible2 = true
            this.queryInfo2.communityId = id
            this.queryshoplist()
        },
        // 点击搜索已经关联的门店
        searchshop() {
            this.queryshoplist()
        },
        // 添加关联门店展示
        findShopListByAdd() {
            this.$http.get('associatedStores/findShopListByAdd', {
                params: this.queryInfo2
            })
                .then(res => {
                    // console.log(res.data)
                    if (res.data.status == 200) {
                        // console.log(res.data.data.list)
                        this.findShopList = res.data.data.list
                        this.total2 = res.data.data.total
                    } else {
                        this.$message.error('服务器接口异常')
                    }
                })
                .catch(error => {
                    this.$message.error('服务器接口异常！')
                })
        },
        // 获取关联门店信息列表
        queryshoplist() {
            this.$http.get('associatedStores/associatedStoresList', {
                params: this.queryInfo2
            })
                .then(res => {
                    // console.log(res.data)
                    if (res.data.status == 200) {
                        // console.log(res.data.data.list)
                        this.associatedStoresList = res.data.data.list
                        this.storeTotal = res.data.data.total
                    } else {
                        this.$message.error('服务器接口异常')
                    }
                })
                .catch(error => {
                    this.$message.error('服务器接口异常！')
                })
        },
        // 删除关联门店
        removeshop(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 引用删除数据接口
                this.$http.post('associatedStores/associatedStoresRemove', {
                    panghuCommunityId: this.queryInfo2.communityId,
                    panghuShopId: id
                })
                    .then(res => {
                        if (res.data.status == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryshoplist()
                            this.queryCommunityList()
                        } else {
                            this.$message({
                                type: 'info',
                                message: '删除失败'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 展示添加小区的对话框
        addcommunity() {
            this.dialogFormVisible = true
            this.title = "新增小区";
            this.community.addOrUpdateFlag = 1;
        },
        // 展示修改的对话框
        editCommunity(row) {
            this.community = row
            this.dialogFormVisible = true;
            this.title = '编辑小区'
            this.address = [row.communityProvince, row.communityCity, row.communityDistrict]
            this.community.addOrUpdateFlag = 2
        },
        // 获取经纬度
        getGeo() {
            // 获取经纬度之前判断是否已经选择过地址
            if (!this.community.communityProvince) {
                this.$message.error('请选择所属地区')
                return false
            }
            // 拼接省市区和详细地址
            let addr = this.community.communityProvince + this.community.communityCity + this.community.communityDistrict + this.community.communityAddress;
            this.$http.get('https://restapi.amap.com/v3/geocode/geo', {
                params: {
                    key: '457886b5972a97e93fb9cdccebfd450f',
                    'address': addr,
                }
            })
                .then(res => {
                    // console.log(res.data.geocodes[0].location)
                    let loc = res.data.geocodes[0].location
                    this.community.communityLongitude = loc.split(',')[0]
                    this.community.communityLatitude = loc.split(',')[1]
                    // console.log(this.community);
                })
        },
        // 添加或修改小区
        updateCommunity() {
            // 先做form表单验证，判断数据合法性
            this.$refs['community'].validate((valid) => {
                if (valid) {
                    this.$http.post('community/communityUpdate', this.community)
                        .then(res => {
                            // console.log(res.data);
                            if (res.data.status == 200) {
                                if (this.community.addOrUpdateFlag == 1) {
                                    this.$message.success('添加成功')
                                } else if (this.community.addOrUpdateFlag == 2) {
                                    this.$message.success('修改成功')
                                }
                                this.dialogFormVisible = false
                                this.queryCommunityList()
                                this.cancel()
                            } else {
                                this.$message.error('操作失败')
                            }
                        })
                } else {
                    this.$message.error('格式有误');
                    return false;
                }
            })

        },
        // 添加或修改的取消
        cancel() {
            this.dialogFormVisible = false
            this.community = {
                communityId: "",       // 编号
                communityName: "",         // 小区名称
                communityAddress: "",     // 详细地址
                communityProvince: "",  // 省份
                communityCity: "",    // 城市
                communityDistrict: "",    // 区域
                communityAreaCode: "",       // 区域码
                communityLatitude: "",     // 纬度
                communityLongitude: "",   // 经度
                communityCoordinates: "",   // 全地址
                addOrUpdateFlag: 1  // 添加还是修改
            }
            this.address = []
        },
        // 获取所有小区信息的函数
        queryCommunityList() {
            // console.log(this.date[0]);
            // console.log(this.date[1]);
            this.$http.get('community/communityList', {
                params: this.queryInfo
            })
                .then(res => {
                    // console.log(res.data)
                    if (res.data.status == 200) {
                        // console.log(res.data.data.list)
                        this.tableData = res.data.data.list
                        // 动态赋予数据总条数
                        this.total = res.data.data.total
                    } else {
                        this.$message.error('服务器接口异常！')
                    }
                })
                .catch(error => {
                    this.$message.error('服务器接口异常！')
                })
        },
        // 删除数据
        removeCommunity(id) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 引用删除数据接口
                this.$http.post('community/communityRemove', {
                    communityId: id
                })
                    .then(res => {
                        if (res.data.status == 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.queryCommunityList()
                        } else {
                            this.$message({
                                type: 'info',
                                message: '删除失败'
                            });
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 小区表格分页方法
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.queryInfo.pageSize = val
            this.queryInfo.pageNum = 1
            this.queryCommunityList()
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.queryInfo.pageNum = val
            this.queryCommunityList()
        },
        // 查看关联门店表格分页方法
        storehandleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.queryInfo2.pageSize = val
            this.queryInfo2.pageNum = 1
            this.queryshoplist()
        },
        storehandleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.queryInfo2.pageNum = val
            this.queryshoplist()
        },
        // 添加关联门店表格分页方法
        handleSizeChange2(val) {
            // console.log(`每页 ${val} 条`);
            this.queryInfo2.pageSize = val
            this.queryInfo2.pageNum = 1
            this.findShopListByAdd()
        },
        handleCurrentChange2(val) {
            // console.log(`当前页: ${val}`);
            this.queryInfo2.pageNum = val
            this.findShopListByAdd()
        },
        // 添加关联门店选择按钮方法
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    },
    // 钩子函数，页面加载后直接执行的代码块
    mounted() {
        this.queryCommunityList()
    },
    // 时间搜索侦听器
    watch: {
        // 要求名称必须和变量名保持一致
        date() {
            if (this.date) {
                this.queryInfo.startTime = this.date[0]
                this.queryInfo.endTime = this.date[1]
            } else {
                this.queryInfo.startTime = ''
                this.queryInfo.endTime = ''
            }
        },
        // 把动态获取的省市区加入到小区对象中
        address() {
            this.community.communityProvince = this.address[0];
            this.community.communityCity = this.address[1];
            this.community.communityDistrict = this.address[2];
        }
    }
}
</script>

<style></style>